<?php

namespace Admin\Model;

use Common\Model\AdminModel;

class AdminInfoModel extends AdminModel
{
    protected $_validate = array(
        array('admin_id','require','账号必须！'),
        array('admin_id', '', '用户名已存在', 0, 'unique', 2), //验证用户是否已存在
        array('admin_pwd','require','密码必须！'),
        array('password_confirm','require','确认密码必须！'),
        array('password_confirm','admin_pwd','确认密码不正确',0,'confirm'), // 验证确认密码是否和密码一致
        array('role_id','require','角色必须！'),
        array('real_name','require','用户姓名必须！'),
    );

    protected $patchValidate = true; //开启批量验证

    /*
     * 管理员登录
     * */
    public function login()
    {
        $post = I("post.");

        if (!empty($post)) {

            $user = M("AdminInfo");

            $where = [];
            $where['admin_id'] = $post['admin_id'];
            $where['admin_pwd'] = md5($post['admin_pwd']);

            $res = $user->where($where)->find();
            if (!empty($res)) {
                $data['id'] = $res['id'];
                $data['last_login_ip'] = gethostbyname(gethostname());
                $data['last_login_time'] = date('Y-m-d H:i:s', time());
                $data['login_count'] = $res['login_count'] + 1;
                $user->data($data)->save();

                $_SESSION['admin'] = [];
                $_SESSION['admin']['admin_id'] = $res['admin_id'];

                return 'ok';
            }else{
                return 'error';
            }
        }
    }

}